function onProductViewLoad() {
    let good = getOneProductData();
    setProductView(good);
}


function getOneProductData(){
    const goodsId = getQueryString("id");
    let good;
    $.ajax({
        url: URL_HEAD_GOODS + TAG_GOODS + "/" + goodsId,
        type: "get",
        async: false,
        success: function (result) {
// alert(result.data.length);l/alert(result.data[0].name);
            // alert(result.data[0].childCategories.length);
            // alert(result.data[0].childCategories[0].name);
            if (result.data !== null) {
                good=result.data;
            } else {
                //商品不存在
            }
        },
        error: function (xhr, textStatus, errorThrown) {
            showError("导入商品详情失败", xhr, textStatus, errorThrown);
        }
    });
    return good;
}


/**
 * 前台商品详情
 * @param good
 * @param builder
 */
function setProductView(good){
    console.log(good)
    const builder = new StringBuilder();
    builder.append("<h1>" + good.name + "</h1>");
    builder.append("<div class=\"infos\">");
    builder.append("<div class=\"thumb\"><img src=\"/images/products/" + good.goodsId + ".png\" style='width:250px; height:250px;'/></div>");
    builder.append("<div class=\"buy\">");
    builder.append("<p>商城价：<span class=\"price\">" + good.price.toString() + "</span></p>");
    builder.append("<p>库　存：" + good.count + "</p>");
    builder.append("<p>上架时间：" + good.createtime.toString() + "</p>");
    builder.append("<p>更新时间：" + good.modifytime.toString() + "</p>");
    builder.append("<div class=\"button\"><input type=\"button\" name=\"button\" value=\"\" onclick=\"goBuy(1)\" /><a href=\"#\">放入购物车</a></div>");
    builder.append("</div>");
    builder.append("<div class=\"clear\"></div>");
    builder.append("</div>");
    builder.append("<div class=\"introduce\">");
    builder.append("<h2><strong>商品详情</strong></h2>");
    builder.append("<div class=\"text\">");
    builder.append(good.description);
    builder.append("</div>");
    builder.append("</div>");
    $("#product").append(builder.toString());
}



function getQueryVariable(variable) {
    var query = window.location.search.substring(1);
    var vars = query.split("&");
    for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split("=");
        if (pair[0] == variable) {
            return pair[1];
        }
    }
    return (false);
}

//后台商品列表
function onProductLoad() {
    $.ajax({
        url: URL_HEAD_GOODS + "/list",
        type: "get",
        success: function (result) {
            const goodsCount = result.data.length;
            if (goodsCount > 0) {
                const builder = new StringBuilder();
                for (let i = 0; i < goodsCount; i++) {
                    const goods = result.data[i];
                    addGoodsTableNewRow(goods, builder);
                    console.log(goods)
                }
            }
        },
        error: function (xhr, textStatus, errorThrown) {
            showError("导入商品管理失败", xhr, textStatus, errorThrown);
        }
    });
}

function addGoodsTableNewRow(goods, builder) {
    builder.clear();
    builder.append("<tr><td class='first w4 c'>");
    builder.append(goods.goodsId)
    builder.append("</td><td class='thumb'><img src=\"../images/products/" + goods.goodsId + ".png\" style='width:55px; height:55px;'/><a href='../product-view.html?id=" + goods.goodsId + "' target='_blank'>");
    builder.append(goods.name);
    builder.append("</a></td><td class='w1 c'><a href='product-modify.html?id=")
    builder.append(goods.goodsId);
    builder.append("'>修改</a> <a href=\"javascript:void(0);\" onclick=\"deleteGood("+goods.goodsId+")\">删除</a></td><tr>");
    $("#tbProductManage tr:last").after(builder.toString());
}

function onGoodsAddLoad() {
    loadCat()
}

/**
 * 商品修改页面加载
 */
function onProductModifyLoad(){
    let good=getOneProductData();
    $("#productName").val(good.name);
    $("#price").val(good.price);
    $("#count").val(good.count);
    $("#description").val(good.description);
    loadCat(good.catId);
}

/**
 * 商品修改和商品添加页面加载分类
 */
function loadCat(catId){
    $.ajax({
        url: URL_HEAD_GOODS + "/childrenCat",
        type: "get",
        success: function (result) {
            const childrenCatCount = result.data.length;
            if (childrenCatCount > 0) {
                const builder = new StringBuilder();
                for (let i = 0; i < childrenCatCount; i++) {
                    const cat = result.data[i];
                    builder.append("<option value='" + cat.catId+"' ");
                    if (cat.catId==catId){
                        builder.append("selected=true");
                    }
                    builder.append(">"+cat.name + "</option>");
                    console.log(cat)
                }
                $("#categories").append(builder.toString());
            }
        },
        error: function (xhr, textStatus, errorThrown) {
            showError("导入商品分类失败", xhr, textStatus, errorThrown);
        }
    });
}


function setWarnPrompt(objOrSelector, prompt) {
    let target = $(objOrSelector);
    target.parent().parent().removeClass();
    let msgBox = target.parent().find("span");
    msgBox.html(prompt);
    msgBox.addClass("error");
}

function checkAndWarnInput(objOrSelector, item, compareSelector) {
    let target = $(objOrSelector);
    if (target.val() === "") {
        setWarnPrompt(objOrSelector, item + "不能为空");
        return false;
    }
    return true;
}

function AddGood() {
    checkAndWarnInput("#productName", "商品名");
    checkAndWarnInput("#categories", "分类");
    checkAndWarnInput("#price", "价格");
    checkAndWarnInput("#count", "库存");
    checkAndWarnInput("#description", "描述");
    const productName = $("#productName").val();
    const category = $("#categories").val();
    const price = $("#price").val();
    const count = $("#count").val();
    const description = $("#description").val();

    $.ajax({
        url: URL_HEAD_GOODS + "/addGood",
        //通过type来判断调用哪个方法
        type: "post",
        data: {
            "name": productName,
            "cat_id": category,
            "price": price,
            "count": count,
            "description": description
        },
        dataType: "json",
        success: function (result) {
            //将页面中存放商品Id的控件值设为新增加的商品Id
            document.getElementById("goodId").value=result.data;

            alert(result.msg);
            if (result.status === 0) {
                //上传图片
                doUpload();
                //跳转到登录页面
               $(location).attr("href", "../manae/product.html");
            }
        },
        error: function (xhr, textStatus, errorThrown) {
            showError("添加异常", xhr, textStatus, errorThrown);
        }
    });
}

function ModifyGood(){
    checkAndWarnInput("#productName", "商品名");
    checkAndWarnInput("#categories", "分类");
    checkAndWarnInput("#price", "价格");
    checkAndWarnInput("#count", "库存");
    checkAndWarnInput("#description", "描述");
    const id=getQueryString("id");
    const productName = $("#productName").val();
    const category = $("#categories").val();
    const price = $("#price").val();
    const count = $("#count").val();
    const description = $("#description").val();
    $.ajax({
        url: URL_HEAD_GOODS + "/updateGood",
        //通过type来判断调用哪个方法
        type: "post",
        data: {
            "id":id,
            "name": productName,
            "catId": category,
            "price": price,
            "count": count,
            "description": description
        },
        dataType: "json",
        success: function (result) {
            document.getElementById("goodId").value=id;

            alert(result.msg);
            if (result.status === 0) {
                //跳转到登录页面
                doUpload();
                $(location).attr("href", "../manae/product.html");
            }
        },
        error: function (xhr, textStatus, errorThrown) {
            showError("修改异常", xhr, textStatus, errorThrown);
        }
    });
}

function deleteGood(goodId) {
    if(confirm("确定要删除吗？")) {
        $.ajax({
            url: URL_HEAD_GOODS + "/deleteGood" + "/" + goodId,
            type: "get",
            async: false,
            success: function (result) {

                if (result.status === 0) {
                    alert("删除成功");
                    location.reload(true);
                } else {
                    alert("删除异常");
                }
            },
            error: function (xhr, textStatus, errorThrown) {
                showError("删除失败", xhr, textStatus, errorThrown);
            }
        });
    }
}


